﻿// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Metadata.Edm;
using System.Data;
using System.Web.UI.WebControls;

namespace EdmMetadataHelpers
{
    /// <summary>
    /// A set of useful extension methods
    /// </summary>
    public static class ExtensionMethods
    {
        /// <summary>
        /// An extension method for a DataTable that allows you to fill the DataTable
        /// with IDataRecords.
        /// 
        /// NOTE: This does no typechecking... i.e. if the DataTable and DataRecords are of different
        /// shapes expect problems.
        /// </summary>
        public static void FillWith(this DataTable table, IEnumerable<IDataRecord> records)
        {
            foreach (IDataRecord record in records)
            {
                DataRow row = table.NewRow();
                foreach (DataColumn column in table.Columns)
                {
                    row[column.ColumnName] = record[column.ColumnName];                  
                }
                table.Rows.Add(row);
            }
        }
        /// <summary>
        /// An extension method that allows you to turn a DataReader
        /// into an iterator over the DataReader's DataRecords
        /// 
        /// This allows DataReaders to work nicely with LINQ i.e. something like this 
        /// becomes possible:
        /// 
        ///  var people = from r in reader.Enumerate()
        ///               select new {Name = r["Name"], Age = r["Age"]};
        /// </summary>
        public static IEnumerable<IDataRecord> Enumerate(this IDataReader reader)
        {
            using (reader)
            {
                while (reader.Read())
                    yield return reader;

                Console.WriteLine("Disposing");
            }
        }
        /// <summary>
        /// A simple utility method that makes a function that is equivalent to string.Format(,) 
        /// accessible via intellisense
        /// </summary>
        public static string Merge(this string template, params string[] values)
        {
            return string.Format(template, values);
        }
    }
}
